package com.qms.tubu.fragment;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.qms.tubu.R;
import com.qms.tubu.activity.MultiPhotoActivity;

import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by Mad on 2015/7/29.
 */
public class PhotoFragment extends BaseFragment {
    private ImageView mZoomImage;
    private PhotoViewAttacher mAttacher;
    private String mImageUrl;
    public static final PhotoFragment getInstance(String imageUrl)
    {
        PhotoFragment photoFragment=new PhotoFragment();
        Bundle bundle=new Bundle();
        bundle.putString("imageurl", imageUrl);
        photoFragment.setArguments(bundle);
        return photoFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getArguments()!=null)
        {
            mImageUrl=getArguments().getString("imageurl");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.fragment_photo,container,false);
        mZoomImage= (ImageView) rootView.findViewById(R.id.zoom_image);
        mAttacher=new PhotoViewAttacher(mZoomImage);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Activity activity=getActivity();
        int width=0;
        int height=0;
        if(activity instanceof MultiPhotoActivity)
        {
            MultiPhotoActivity multiPhotoActivity= (MultiPhotoActivity) activity;
            width=multiPhotoActivity.getWidth();
            height=multiPhotoActivity.getHeight();
        }
        Glide.with(this).load(mImageUrl).asBitmap().into(new SimpleTarget<Bitmap>(width,height) {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                mZoomImage.setImageBitmap(resource);
                mAttacher.update();
            }
        });
    }

    @Override
    public void onStop() {
        mAttacher.setScale(1);
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        mAttacher.cleanup();
        super.onDestroyView();
    }
}
